import json
import threading
import pyautogui as pg
from pynput import keyboard
import pandas as pd
import os
from time import sleep
from platform import system
from scripts_env.snapshot import gnome_screenshot
from scripts_env.paint_area import rect_img

pg.FAILSAFE = False
play_flag = True


def select_screenshot(image_path):
    if system() == 'Windows':
        pass
    elif system() == 'Linux':
        t = gnome_screenshot(image_path)
        return t


def on_press(key):
    if key == keyboard.Key.esc:
        global play_flag
        play_flag = False
        return False


def on_release(key):
    if key == keyboard.Key.esc:
        return False


def exit_replay():
    with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()


def run(data_path, image_path):
    if not os.path.exists(image_path):
        os.makedirs(image_path)
    if os.path.exists(data_path) and os.path.isfile(data_path):
        record_data = pd.read_csv(data_path, index_col=0)
        if '比对区域' not in record_data.columns.to_list():
            record_data.columns.to_list().insert(4, '比对区域')
            record_data.reindex(columns=record_data.columns.to_list())
            record_data.insert(loc=4, column='比对区域', value='nan')
        if '相似度' not in record_data.columns.to_list():
            record_data.columns.to_list().insert(5, '相似度')
            record_data.reindex(columns=record_data.columns.to_list())
            record_data.insert(loc=5, column='相似度', value='nan')
        if '结果' not in record_data.columns.to_list():
            record_data.columns.to_list().insert(6, '结果')
            record_data.reindex(columns=record_data.columns.to_list())
            record_data.insert(loc=6, column='结果', value='nan')
        record_data.to_csv(
            data_path, columns=record_data.columns.to_list(), encoding='utf_8_sig')
        all_step = record_data.shape[0]
        home_path = os.path.expanduser('~')
        conf_file = os.path.join(home_path, '.lance')
        is_replay = False
        if os.path.exists(conf_file):
            with open(conf_file, 'r', encoding='utf-8') as file:
                data = json.load(file)
                is_replay = data['is_replay']
                print("是否是回放操作:", is_replay)
        if is_replay:
            e = threading.Thread(target=exit_replay)
            e.start()
        record_data = pd.read_csv(data_path, index_col=0)
        for run_step in range(0, record_data.shape[0]):
            click_delay = record_data.iloc[run_step, 0]
            press_type = record_data.iloc[run_step, 1]
            event_type = record_data.iloc[run_step, 2]
            input_data = eval(
                record_data.iloc[run_step, 3].replace("", ""))
            sleep(click_delay/1000.0)
            if play_flag == False:
                break
            if event_type == 'mouse move':
                pg.moveTo(
                    int(input_data[0]), int(input_data[1]), tween=pg.easeInBounce)
            if event_type == 'mouse left down':
                pg.mouseDown(
                    int(input_data[0]), int(input_data[1]), button='left')
            if event_type == 'mouse left up':
                next_up = run_step+2
                if next_up < all_step and system() == 'Linux':
                    next_press_type = record_data.iloc[next_up, 1]
                    next_event_type = record_data.iloc[next_up, 2]
                    next_input_data = eval(
                        record_data.iloc[next_up, 3].replace("", ""))
                    if event_type == next_event_type and input_data == next_input_data:
                        run_step = next_up
                        pg.click(int(input_data[0]), int(
                            input_data[1]), clicks=2)
                pg.mouseUp(int(input_data[0]), int(
                    input_data[1]), button='left')
                image_file = os.path.join(
                    image_path, str(run_step+1) + '.png')
                select_screenshot(image_file)
                roi = record_data.at[int(run_step+1), '比对区域']
                if not pd.isna(roi):
                    rect_img(image_file, roi, 0)
            if event_type == 'mouse right down':
                pg.mouseDown(
                    int(input_data[0]), int(input_data[1]), button='right')
            if event_type == 'mouse right up':
                pg.mouseUp(int(input_data[0]), int(
                    input_data[1]), button='right')
                image_file = os.path.join(
                    image_path, str(run_step+1) + '.png')
                select_screenshot(image_file)
                roi = record_data.at[int(run_step), '比对区域']
                # if not pd.isna(roi):
                #     rect_img(image_file, roi, 0)
# -------------------------------------------------------------------------------------------------------
            if event_type == 'mouse wheel down':
                if click_delay < 10:
                    run_step += 2
                    cmd = 'xdotool click 5 sleep '+str(click_delay/1000)
                    os.system(cmd)
            if event_type == 'mouse wheel up':
                if click_delay < 10:
                    run_step += 2
                    cmd = 'xdotool click 4 sleep '+str(click_delay/1000)
                    os.system(cmd)
# -------------------------------------------------------------------------------------------------------
            if event_type == 'mouse middle down':
                pg.mouseDown(button='middle')
            if event_type == 'mouse middle up':
                pg.mouseUp(button='middle')
            if event_type == 'key down':
                pg.keyDown(input_data[0])
            if event_type == 'key up':
                pg.keyUp(input_data[0])
